﻿#include "formsetting.h"
#include "ui_formsetting.h"
#include <QCloseEvent>
#include <QSettings>
#include <QMessageBox>
#include <QFileDialog>
#include <QAbstractItemDelegate>
#include <QDebug>
#include "../widget.h"
#include "../utils/winmanager.h"
#ifdef Q_OS_WIN
#include <QtWin>
#endif
FormSetting::FormSetting(QMap<int, QString> _mapGroupIp, QWidget *parent) ://_GroupIpList
    QWidget(parent),_IsAddDate(false),
    ui(new Ui::FormSetting)
{
    ui->setupUi(this);
    setWindowModality(Qt::ApplicationModal);
    setAttribute(Qt::WA_DeleteOnClose);
    m_mapGroupIp = _mapGroupIp;

    ui->line_setwindowTitle->installEventFilter(this);

    ui->line_setwindowTitle->setReadOnly(true);
    ui->line_setwindowTitle->setStyleSheet("background:rgba(225,225,225,220);");

    ui->tableGroupView->setItemDelegateForColumn(0,new ReadOnlyDelegate(this));
    ui->tableGroupView->setItemDelegateForColumn(1,new LineEditDelegate(this));
    ui->tableGroupView->setItemDelegateForColumn(2,new ReadOnlyDelegate(this));
//    ui->tableGroupView->setItemDelegateForColumn(3,new DeleteButton(this));
//    ui->tableGroupView->resizeColumnsToContents();
//    ui->tableGroupView->horizontalHeader()->resizeSections(QHeaderView::Stretch);

    QRegExp regExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    ui->lineAddIpadd->setValidator(new QRegExpValidator(regExp, this));

    connect(ui->lineAddIpadd,&QLineEdit::textChanged,[=](const QString & text){
        ui->btnAddGroup->setEnabled(!text.isEmpty());
    });

    ipList.clear();

    QSettings setting;

    //window title setting
    ui->line_setwindowTitle->setText(setting.value("general/appTitle","").toString());

    setting.beginGroup("general");
    bool isshow = setting.value("IsShowDebug",false).toBool();
    setting.endGroup();
    ui->cb_showdebug->setChecked(isshow);
    connect(ui->cb_showdebug,&QCheckBox::stateChanged,[=](int state){
        QSettings setting1;
        setting1.beginGroup("general");
        setting1.setValue("IsShowDebug",state);
        setting1.endGroup();
    });

    ui->tableGroupView->removeRow(0);

    setting.beginGroup("GroupData");
    ui->tableGroupView->clear();
    //Update Header View
    QStringList listHeader = QStringList()<<QStringLiteral("组号")<<QStringLiteral("IP地址")<<QStringLiteral("连接状态");
    ui->tableGroupView->setHorizontalHeaderLabels(listHeader);

    foreach(QString ipadd,_mapGroupIp)
    {
        ipList.append(ipadd);
        ui->tableGroupView->insertRow(ui->tableGroupView->rowCount());

//        qDebug()<<_mapGroupIp.count()<<ipadd<<(ui->tableGroupView->rowCount());
        for(int j = 0;j<ui->tableGroupView->horizontalHeader()->count();j++){
            QString text;
            switch(j){
            case 0:
                text = QString::number(ui->tableGroupView->rowCount());
                break;
            case 1:
                text = ipadd;
                break;
            case 2:
                text = QStringLiteral("未连接");
                break;
            }
            QTableWidgetItem *item = new QTableWidgetItem(text);
            item->setTextAlignment(Qt::AlignCenter);
            int row = ui->tableGroupView->rowCount()-1;
            ui->tableGroupView->setItem(row,j,item);
        }
    }
    setting.endGroup();

    setting.beginGroup("AppData/Operate");
    bool flag_firstStart = setting.value("FirstStart",true).toBool();
    if(flag_firstStart)
        setting.setValue("FirstStart",false);
    setting.endGroup();


    connect(ui->lineAddDelyTime,&QLineEdit::textChanged,[=]{
        ui->btnAddDelayTime->setEnabled(!ui->lineAddDelyTime->text().isEmpty());
    });

    //添加分组按钮功能
    connect(ui->btnAddGroup,&QToolButton::clicked,[=]{
        AddItem();
    });
    //删除最后一组按钮功能
    connect(ui->btnDeleteItem,&QToolButton::clicked,[=]{
        ui->btnDeleteItem->setEnabled(ui->tableGroupView->rowCount()-1);
        if(ui->tableGroupView->rowCount()){
            if((ui->tableGroupView->rowCount()-1))
            {
                ui->tableGroupView->removeRow(ui->tableGroupView->rowCount()-1);
            }
            else {
                ui->tableGroupView->removeRow(0);
            }
            ipList.removeLast();//ui->tableGroupView->item(ui->tableGroupView->rowCount()-1,1)->text());
            QSettings setting;
            setting.beginGroup("GroupData");
            setting.remove(QString::number(ui->tableGroupView->rowCount()+1));
            m_mapGroupIp.remove(ui->tableGroupView->rowCount()+1);
            setting.sync();
            setting.endGroup();
            ui->tableGroupView->selectRow(ui->tableGroupView->rowCount()-1);
            ui->tableGroupView->setFocus();
            _IsAddDate = true;
        }
    });

    //Group Folder setting
    connect(ui->btnFolderChange,&QToolButton::clicked,[=]{
        QString path = QFileDialog::getExistingDirectory(this,"",QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/data/Groupdata");
        if(!path.isEmpty())
            ui->lineFolder->setText(path);
    });
    connect(ui->lineFolder,&QLineEdit::textChanged,[=]{
        if(!ui->lineFolder->text().isEmpty()){
            QDir dir(ui->lineFolder->text());
            if(dir.exists()){
                QSettings setting;
                setting.setValue("general/DefaultSaveDir",ui->lineFolder->text());
                setting.sync();
            }
        }
    });

    connect(ui->lineFolder,&QLineEdit::textEdited,[=]{
        if(!ui->lineFolder->text().isEmpty()){
            ui->lineFolder->setCursorPosition(0);
            ui->lineFolder->selectAll();
        }
    });
    connect(ui->lineFolder,&QLineEdit::editingFinished,[=]{
        ui->lineFolder->setCursorPosition(0);
    });
    connect(ui->cb_close,&QCheckBox::stateChanged,[=]{
        QSettings setting;
        setting.setValue("AppData/CloseAppNotQuit",ui->cb_close->isChecked());
    });

    connect(ui->tableGroupView,&QTableWidget::cellPressed,[=](int row, int column){
        qDebug()<<"item Change:"<<ui->tableGroupView->item(row,column)->text();
    });

    //widget Property
    ui->btnDeleteItem->setEnabled(ui->tableGroupView->rowCount());//删除按钮-没有可用分组时按钮不可用

    //load setting.
    ui->lineFolder->setText(setting.value("general/DefaultSaveDir",
                                          QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/data/").toString());
    ui->lineFolder->setCursorPosition(0);

    //Lined IPAdd,增加分组IP输入控件属性设置
    ui->lineAddIpadd->setClearButtonEnabled(true);//添加清除按钮
    ui->lineAddIpadd->installEventFilter(this);
    //Lined Delay ,延时输入控件属性设置
    ui->lineAddDelyTime->setClearButtonEnabled(true);

    //App close to hide
    ui->cb_close->setChecked(setting.value("AppData/CloseAppNotQuit",true).toBool());
    {
        int statDataImport = setting.value("general/DataImportHandle",QByteArray("-1")).toByteArray().toInt();
        if(statDataImport<0){
            ui->lblDataImportSet->setText(QStringLiteral("(<span style=\" color:#afafaf;\">自动导入</span>/<span style=\" color:#afafaf;\">手动导入</span>)"));
            ui->cbDataImportSet->setChecked(false);
            ui->cbDataImportSet->setToolTip(QStringLiteral("未设定"));
            ui->lblDataImportSet->setToolTip(ui->cbDataImportSet->toolTip());
        }else
            ui->cbDataImportSet->setChecked(statDataImport);

        //NOTE:should add after date set.
        connect(ui->cbDataImportSet,&QCheckBox::stateChanged,[=](int state){
            QSettings setting;
            setting.beginGroup("general");
            setting.setValue("DataImportHandle",QVariant(QString::number(state).toLatin1()));
            setting.endGroup();
            state?ui->lblDataImportSet->setText(QStringLiteral("(<span style=\" font-weight:600; color:#0000ff;\">自动导入</span>/<span style=\" color:#afafaf;\">手动导入</span>)")):
                  ui->lblDataImportSet->setText(QStringLiteral("(<span style=\" color:#afafaf;\">自动导入</span>/<span style=\" font-weight:600; color:#0000ff;\">手动导入</span>)"));
            ui->cbDataImportSet->setToolTip(QString(QStringLiteral("数据")+"%1"+QStringLiteral("导入")).arg(state?QStringLiteral("自动"):QStringLiteral("手动")));
            ui->lblDataImportSet->setToolTip(ui->cbDataImportSet->toolTip());
        });
    }

    //style sheet
    ui->tabWidget->setObjectName("FormsettingTabWidget_");
    ui->tabWidget->setStyleSheet(QString("QTabWidget#%1{background-color:rgba(238,238,238,255);}").arg(ui->tabWidget->objectName()));

//#ifdef Q_OS_WIN
//    if (QtWin::isCompositionEnabled()) {
//        QtWin::extendFrameIntoClientArea(this, -1, -1, -1, -1);
//        setAttribute(Qt::WA_TranslucentBackground, true);
//        setAttribute(Qt::WA_NoSystemBackground, false);
//        setStyleSheet(QString("%1 { background: transparent; }").arg(objectName()));
//    }
//    else {
//        QtWin::resetExtendedFrame(this);
//        setAttribute(Qt::WA_TranslucentBackground, false);
//        setStyleSheet(QString("%2 { background: %1; }").arg(QtWin::realColorizationColor().name(),objectName()));
//    }
//#endif
}

FormSetting::~FormSetting()
{
    delete ui;
}

void FormSetting::setupGroupToTable()
{
    //    ui->tableGroupView->setItem();
}


bool FormSetting::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == ui->lineAddIpadd){
        if(event->type() == QKeyEvent::KeyRelease){
            QKeyEvent *keyevent = static_cast<QKeyEvent*>(event);//事件过滤处理-IP字段输入完后可通过按回车进行添加
            if(keyevent->key() == Qt::Key_Return || keyevent->key() == Qt::Key_Enter)
            {
                AddItem();
            }
        }
    }
    if(obj == ui->line_setwindowTitle){
        if(event->type() == QMouseEvent::MouseButtonPress){
            if(static_cast<QMouseEvent*>(event)->button() == Qt::LeftButton){
//                ui->line_setwindowTitle->setEnabled(true);
//                ui->line_setwindowTitle->setCursorPosition(0);
                ui->line_setwindowTitle->setReadOnly(false);
                ui->line_setwindowTitle->setStyleSheet("background:white;");
                return false;
            }
        }
        if(event->type() == QFocusEvent::FocusOut){
            ui->line_setwindowTitle->setReadOnly(true);
            ui->line_setwindowTitle->setStyleSheet("background:rgba(225,225,225,220);");
            QSettings setting;
            setting.setValue("general/appTitle",ui->line_setwindowTitle->text());
            setting.sync();
//            ui->line_setwindowTitle->setEnabled(false);
        }

    }
    return QWidget::eventFilter(obj,event);
}

void FormSetting::AddItem()
{
    QRegExp regExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    if(!ui->lineAddIpadd->text().contains(regExp)){
        QMessageBox::warning(0,QStringLiteral("提示"),
                             QStringLiteral("<h4>当前输入IP地址不合法，请填写正确后再添加!</h4><br/>"), QMessageBox::Ok);
        ui->btnAddGroup->setFocus();
        return;
    }
    _IsAddDate = true;
    if(ui->tableGroupView->rowCount())
        ui->btnDeleteItem->setEnabled(true);
    //判斷已有列表中的IP是否有重覆
    if(!ipList.contains(ui->lineAddIpadd->text())){
        QSettings setting;
        setting.beginGroup("GroupData");
        ui->tableGroupView->insertRow(ui->tableGroupView->rowCount());
        ipList.append(ui->lineAddIpadd->text());

        for(int i = 0;i<ui->tableGroupView->horizontalHeader()->count();i++){
            QString text;
            switch(i){
            case 0:
                text = QString::number(ui->tableGroupView->rowCount());
                break;
            case 1:
                text = ui->lineAddIpadd->text();
                break;
            case 2:
                text = QStringLiteral("未连接");
                break;
            }
            QTableWidgetItem *item = new QTableWidgetItem(text);
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableGroupView->setItem(ui->tableGroupView->rowCount()-1,i,item);
        }
        setting.setValue(QString("%1/IpAdd").arg(QString::number(ui->tableGroupView->rowCount())),
                                                ui->lineAddIpadd->text());
        setting.setValue(QString("%1/States").arg(QString::number(ui->tableGroupView->rowCount())),
                         false);
//        QString path = setting.value("general/DefaultSaveDir",QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/data/").toString()+
//                QString::number(ui->tableGroupView->rowCount());
//        QDir dir(path);
//        if(!dir.exists())
//            dir.mkpath(path);
        m_mapGroupIp.insert(ui->tableGroupView->rowCount(),ui->lineAddIpadd->text());
        setting.sync();
        setting.endGroup();
    }else{
        QMessageBox::warning(0,QStringLiteral("提示"),
                             QStringLiteral("<h4>当前已有相同IP，请检察输入内容后再重新添加!</h4><p></p>")
                              + QString(QStringLiteral("相同组号为: 第%2组")).arg(QString::number(ipList.indexOf(ui->lineAddIpadd->text())+1)), QMessageBox::Ok);
        ui->tableGroupView->selectRow(ipList.indexOf(ui->lineAddIpadd->text()));
        ui->tableGroupView->setFocus();
    }
}

void FormSetting::closeEvent(QCloseEvent *event)
{
    QSettings setting;
    setting.beginGroup("GroupData");

    for(int i=0;i<ui->tableGroupView->rowCount();i++){
        setting.setValue(QString("%1/IpAdd").arg(ui->tableGroupView->item(i,0)->text()),
                                                ui->tableGroupView->item(i,1)->text());
        m_mapGroupIp.insert(ui->tableGroupView->item(i,0)->text().toInt(),ui->tableGroupView->item(i,1)->text());
    }
    emit onClose(_IsAddDate,m_mapGroupIp);

    event->accept();
    setParent(0);
//    if(this->parent())
}

/// Delegate of LineEdit.
QWidget *LineEditDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const
{
    QLineEdit *editor = new QLineEdit(parent);
    QRegExp regExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    editor->setValidator(new QRegExpValidator(regExp, parent));
    editor->setAlignment(Qt::AlignCenter);
    connect(editor,&QLineEdit::textEdited,this,&LineEditDelegate::finishEdEdit);
//    connect(editor,&QLineEdit::textEdited,[=](const QString &){
//            qDebug()<<"delegate.edit finished--"<<editor->text();
//            emit *LineEditDelegate::finishEdEdit(editor->text());
////            setEditorData(editor,index);
//    });
    return editor;
}

void LineEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString text = index.model()->data(index, Qt::EditRole).toString();
    QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);

    lineEdit->setText(text);
}

void LineEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
    QString text = lineEdit->text();
    model->setData(index, text, Qt::EditRole);
}

void LineEditDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const
{
    editor->setGeometry(option.rect);
}

